package cn.yerly.learning_code.io.bio;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

import cn.yerly.learning_code.io.entity.MyRequestObject;
import cn.yerly.learning_code.io.entity.MyResponseObject;

/**
 * bio server
 * Created by yerly on 2015/5/11.
 */
public class Server {
    private final static Logger logger = Logger.getLogger(Server.class.getName());
	private static ServerSocket serverSocket;
    public static void main(String[] args) throws IOException {
        serverSocket = new ServerSocket(9999);
        while (true) {
            Socket s = serverSocket.accept();
            new Entry(s).start();
        }
    }


    private static final class Entry extends Thread {
        private Socket s;
        public Entry(Socket s) {
            this.s = s;
        }
        @Override
        public void run() {
            ObjectOutputStream os = null;
            ObjectInputStream is = null;
            try {
                os = new ObjectOutputStream(s.getOutputStream());
                is = new ObjectInputStream(s.getInputStream());
                MyRequestObject r = (MyRequestObject) is.readObject();
                logger.log(Level.INFO, r.toString());

                MyResponseObject myResponseObject = new MyResponseObject(
                        "response for " + r.getName(),
                        "response for " + r.getValue());
                os.writeObject(myResponseObject);
                logger.log(Level.INFO, myResponseObject.toString());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (os != null) {
                        os.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
